<script setup>
import {nextTick, reactive, ref} from 'vue'
import {ElMessage} from "element-plus";
import {addFixtureLedger, findFixtureLedgerById} from "@/apis/zyj/FixtureLedger.js";

const props = defineProps({
  addDialog: Boolean,
  typeDate: Array
})

const isSwitch = ref(false)
const formRef = ref()
const form = reactive({
  typeCode: '',
  fixtureName: '',
  brand: '',
  model: '',
  fixtureCode: '',
  quantity: '',
  availableQuantity: '',
  maintenanceType: '定期维护',
  nextMaintenanceDate: '',
  nextMaintenancePeriod: '',
  status: '0',
  remark: ''
})
const ruleForm = reactive({...form})

// 校验编码是否重复
const validateCode = (rule, value, callback) => {
  findFixtureLedgerById(value).then(res => {
    console.log(res)
    if (res) {
      callback(new Error('该编码已存在'))
    } else {
      callback()
    }
  })
}

const rules = {
  typeCode: [
    {required: true, message: '请选择工装夹具类型', trigger: 'change'},
  ],
  fixtureName: [{required: true, message: '请输入工装夹具名称', trigger: 'blur'}],
  quantity: [{required: true, message: '请输入数量', trigger: 'blur'}],
  fixtureCode: [
    {required: true, message: '请输入工装夹具编号', trigger: 'blur'},
    {validator: validateCode, trigger: 'blur'}
  ]
}

// 自定义事件
const emit = defineEmits(['close-dialog'])
// 关闭弹窗
const handleClose = () => {
  isSwitch.value = false
  Object.assign(form, ruleForm)
  emit('close-dialog')
}
// 打开弹窗时清空校验
const handleOpenCardDialog = () => {
  nextTick(() => {
    // 清空校验
    formRef.value.clearValidate()
  })
}
const handleSubmit = async () => {
  // 验证forRef是否存在
  if (!formRef.value) return
  console.log(form)
  try {
    await formRef.value.validate()
    // 在此处处理表单提交
    addFixtureLedger(form).then(req => {
      console.log(req)
      if (req === '成功') {
        ElMessage.success('添加成功')
        handleClose()
      } else {
        ElMessage.error('添加失败')
      }
    })
  } catch (error) {
    ElMessage.error('请填写完整信息')
  }
}

function createID() {
  let code = 'T';
  let date = new Date();
  let year = date.getFullYear();
  let month = date.getMonth() + 1;
  let strDate = date.getDate();
  code = code + year + month + strDate + Math.floor(Math.random() * 10000);
  console.log(code)
  return code;
}

// 自动生成员工编码
const switchCode = (value) => {
  let code = createID();
  if (value) {
    form.fixtureCode = code
  } else {
    form.fixtureCode = ''
  }
}
const eventDisposalRangeChange = () => {
  form.availableQuantity = form.quantity
}
</script>

<template>
  <el-dialog title="添加工装夹具清单" v-model="props.addDialog" width="60%" @close="handleClose"
             @open="handleOpenCardDialog">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" class="equipment-form">
      <el-row>
        <el-col :span="12">
          <el-form-item label="工装夹具类型" prop="typeCode">
            <el-select v-model="form.typeCode" placeholder="请选择类型" class="w-full" style="width: 200px;">
              <el-option v-for="s in props.typeDate" :label="s.typeName" :value="s.typeCode"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="工装夹具名称" prop="fixtureName">
            <el-input v-model="form.fixtureName" placeholder="请输入工装夹具名称"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="品牌">
            <el-input v-model="form.brand" placeholder="请输入品牌"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="型号">
            <el-input v-model="form.model" placeholder="请输入型号"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="8">
          <el-form-item label="工装夹具编号" prop="fixtureCode">
            <div class="flex items-center">
              <el-input v-model="form.fixtureCode" placeholder="请输入工装夹具编号"/>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-switch
              v-model="isSwitch"
              class="ml-2"
              @change="switchCode"
              active-text="自动生成"
          />
        </el-col>
        <el-col :span="12">
          <el-form-item label="数量" prop="quantity">
            <el-input-number
                v-model="form.quantity"
                min="0"
                controls-position="right"
                class="w-full"
                @blur="eventDisposalRangeChange"
                @input.native="eventDisposalRangeChange"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="可用数量">
            <el-input
                v-model="form.availableQuantity"
                placeholder="请输入可用数量"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="保养维护类型">
            <el-select v-model="form.maintenanceType" placeholder="请选择维护类型" class="w-full">
              <el-option label="定期维护" value="定期维护"/>
              <el-option label="按使用次数维护" value="按使用次数维护"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item v-if="form.maintenanceType === '定期维护'" label="下一次保养日期">
            <el-date-picker
                v-model="form.nextMaintenanceDate"
                type="date"
                placeholder="请选择下一次保养日期"
                class="w-full"
            />
          </el-form-item>
          <el-form-item v-if="form.maintenanceType === '按使用次数维护'" label="下一次保养周期">
            <el-input v-model="form.nextMaintenancePeriod" placeholder="请输入保养周期"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态">
            <el-radio-group v-model="form.status">
              <el-radio label="1">在库</el-radio>
              <el-radio label="2">被领用</el-radio>
              <el-radio label="3">报废</el-radio>
              <el-radio label="4">维修中</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="备注">
        <el-input
            v-model="form.remark"
            type="textarea"
            rows="4"
            placeholder="请输入内容"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.equipment-form {
  max-height: 60vh;
  overflow-y: auto;
  padding-right: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.el-form-item__label) {
  font-weight: normal;
}

:deep(.el-input-number .el-input__wrapper) {
  width: 100%;
}

.w-full {
  width: 100px;
}
</style>